<?php

namespace app\index\controller;

use app\common\entity\MywalletLog;
use app\common\entity\User;
use app\index\model\SendCode;
use app\index\model\SiteAuth;
use app\index\validate\RegisterForm;
use app\common\service\Users\Service;
use think\Controller;
use think\Db;
use think\facade\Lang;
use think\Request;
use app\common\entity\Config;
use app\common\entity\UserLevelSend;
use app\common\entity\UserInviteCode;
use app\common\entity\Article;
use app\common\service\Users\Identity;
use think\facade\Session;
use app\index\controller\Base;
use app\index\model\aliyun\api_demo\SmsDemo;

class Publics extends Common
{

    /**
     * [获取审核状态]
     * @param
     * @return
     */
    public function smsss( Request $request ){


        $response = SmsDemo::sendSms();
        echo "发送短信(sendSms)接口返回的结果:\n";
        print_r($response);
    }

    public function initialize()
    {

        $switch = SiteAuth::checkSite();
        if ($switch !== true) {
            if (request()->isAjax()) {
                return json(['code' => 1, 'message' => $switch]);
            } else {
                (new SiteAuth())->alert($switch);
            }
        }
        parent::initialize();
    }

    public function lang(){
        echo Lang::detect();
    }
    public function set_lang($lang){
        switch ($lang){
            case 'cn':
                Lang::setLangDetectVar('zh-cn');
                break;
            case 'en':
                Lang::setLangDetectVar('en-us');
                break;
        }
        echo $lang;
    }

    public function is_login(){

        $identity = new Identity();
        $userId = $identity->getUserId();
        $info = User::where('id', $userId)->find();
        Session::set('username', $info['nick_name']);

       if ($info['login_time'] != session_id()) {
            return json(['code' => 10, 'message' => '登录失效，请重新登录', 'url' => 'login','info'=>$userId]);
        }
        if ($userId) {
            return json(['code' => 0, 'message' => 'yes', 'info' =>$userId]);
        }
        return json(['code' => 10, 'message' => '可登陆', 'url' => 'login']);
    }

    public function index(Request $request)
    {
        header("Location:/dist/#/");die;
        return $this->fetch('index');

        $domain = $request->domain();
        $this->redirect($domain . '/index/login.html');
//        return $this->fetch('login');

    }

    //登录处理
    public function login(Request $request)
    {

        $is_can_login = Config::getValue('is_can_login');//WithdrawRatio::where('key', 'is_can_login')->value('ratio');
        if ($is_can_login == 0) {

            return json(['code' => 1, 'message' => '系统升级维护中....']);
        }

        $result = $this->validate($request->post(), 'app\index\validate\LoginForm');
        if ($result !== true) {
            return json(['code' => 1, 'message' => $result]);
        }
        $model = new \app\index\model\User();
        $result = $model->doLogin($request->post('account'), $request->post('password'));

        if ($result !== true) {
            return json(['code' => 1, 'message' => $result]);
        }
        $user = new \app\common\model\User();

        $get_user = $user->getUser($request->post('account'), 'mobile');
        // 更新最后登录时间
        //$get_user->save(['login_time' => time(), 'last_date' => date('Y/m/d'), 'login_ip' => $request->ip()]);
        unset($get_user['password']);
        session('home_user', $get_user);
        //session('login_time', time());
        /*if($get_user['real_pass'] != 2){
            return json(['code' => 2, 'message' => '请实名认证']);
        }*/


        return json(['code' => 0, 'message' => '登录成功', 'info' => ['id' => $get_user['id']], 'toUrl' => url('index/index'),'token'=>$get_user['login_time']]);
    }




    #注册
    public function doRegister(Request $request)
    {



        $model = new \app\index\model\User();
        $is_register = Config::getValue('is_register');//WithdrawRatio::where('key', 'is_register')->value('ratio');
        //$mobile_can_num = Config::getValue('mobile_can_num');//WithdrawRatio::where('key', 'mobile_can_num')->value('ratio');
        //$everyday_reg_num = Config::getValue('everyday_reg_num');//WithdrawRatio::where('key', 'everyday_reg_num')->value('ratio');
        if ($is_register == 0) {

//            return json(['code' => 1, 'message' => '系统升级中，暂停注册']);
        }

//        $today_reg = User::whereTime('register_time', 'today')->count();
//        if ($today_reg >= $everyday_reg_num) {
//            return json(['code' => 1, 'message' => '今日注册会员已达上限']);

//        }
        // if (!$model->checkRegisterOpen()) {
        //     return json(['code' => 1, 'message' => '平台已关闭注册了']);
        // }
        if (!$model->checkIp()) {
//            return json(['code' => 1, 'message' => '兄弟，好像注册太多了哦']);
        }

        $name_first = substr($request->post('nick_name'), 0, 1);
       /* if (is_numeric($name_first)) {

            return json(['code' => 1, 'message' => '账号必须已字母开头']);

        }*/

        $is_mobile_count = User::where('mobile', $request->post('mobile'))->find();
        if ($is_mobile_count) {
            return json(['code' => 1, 'message' => '该手机号码已注册']);
        }
        /*$is_nick_name = User::where('nick_name', $request->post('nick_name'))->find();
        if ($is_nick_name) {
            return json(['code' => 1, 'message' => '该账号已注册']);
        }*/

//        $is_zfb_has = User::where('zfb',$request->post('zfb'))->find();
//        if ($is_zfb_has) {
//           return json(['code' => 1, 'message' => '该支付宝号已经被绑定了']);
//        }
        $validate = $this->validate($request->post(), '\app\index\validate\RegisterForm');
        if ($validate !== true) {
            return json(['code' => 1, 'message' => $validate]);
        }

        $form = new RegisterForm();
        if (!$form->checkCode($request->post('code'), $request->post('mobile'))) {
//	         return json(['code' => 1, 'message' => '验证码输入错误']);
        }
        //注册处理
        $result = $model->doRegister($request->post());
        if ($result) {
            $user_id = Db::table('user')->where('mobile', $request->post('mobile'))->field('id,pid')->find();

            return json(['code' => 0, 'message' => '注册成功', 'info' => $user_id]);
//            MywalletLog::addLog($user_id['id'],Config::getValue('lock_register'), 2, '注册赠送', 9, 1);
//            $send_num = WithdrawRatio::where('key','send_num')->value('ratio');
//            $machineModel = new MachineList();
//            $machineModel->insMachine($user_id['id'], 1, 0, $send_num);



        }
        return json(['code' => 1, 'message' => '注册失败']);
    }

    //发送注册验证码
    public function send_info(){
        $model = new SendCode('13073087160', 'info');
        print_r($model->sendInfo('【卡商天下】您本次出售的订单已经开始匹配，请您及时查收是否到账，到账及时线上进行确认，超过三小时不确认，账号会被冻结，谢谢您的配合。'));
    }

    public function send(Request $request)
    {
        if ($request->isPost()) {
            $mobile = $request->post('mobile');
            //检验手机号码
            if (!preg_match('#^1\d{10}$#', $mobile)) {
                return json(['code' => 1, 'message' => '手机号码格式不正确', 'info' => $mobile]);
            }
            #判断手机号码是否已被注册
            if (User::checkMobile($mobile)) {
                return json(['code' => 1, 'message' => '此账号已被注册，请重新填写']);
            }
            $model = new SendCode($mobile, 'register');
            if ($model->send()) {
                return json(['code' => 0, 'message' => '你的验证码发送成功']);
            }


            return json(['code' => 1, 'message' => '发送失败']);
        }
    }

    //找回密码
    public function change()
    {
        return $this->fetch('change');
    }

    //发送找回密码验证码
    public function sendChange(Request $request)
    {
        if ($request->isPost()) {
            $mobile = $request->post('mobile');
            //检验手机号码
            if (!preg_match('#^1\d{10}$#', $mobile, $m)) {
                return json(['code' => 1, 'message' => '手机号码格式不正确']);
            }
            //判断手机号码是否注册
            if (!User::checkMobile($mobile)) {
                return json(['code' => 1, 'message' => '此账号不存在，请重新填写']);
            }
            $model = new SendCode($mobile, 'change-password');
            if ($model->send()) {
                return json(['code' => 0, 'message' => '你的验证码发送成功.']);//.$model->code
            }

            return json(['code' => 1, 'message' => '发送失败']);
        }
    }


    /**
     * 找回密码 修改密码
     */
    public function changeSave(Request $request)
    {
        $mobile = $request->post("mobile");
        //检验手机号码
        if (!preg_match('#^1\d{10}$#', $mobile)) {
            return json(['code' => 1, 'message' => '手机号码格式不正确']);
        }
        $user = User::where("mobile", $mobile)->find();
        //判断手机号码是否注册
        if (!User::checkMobile($mobile)) {
            return json(['code' => 1, 'message' => '此账号不存在，请重新填写']);
        }

        $new_pwd = $request->post("new_pwd"); //新密码
        $confirm_pwd = $request->post("confirm_pwd"); //确认密码
        //$new_trad_pwd = $request->post("trad_pwd"); //新交易密码
        //$confirm_trad_pwd = $request->post("confirm_trad_pwd"); //确认交易密码

        $service = new Service();
        if ($service->getPassword($new_pwd) == $user->password) {
            return json(['code' => 1, 'message' => '登录密码没变']);
        }

        if (strlen($new_pwd) < 6) {
            return json(['code' => 1, 'message' => '登录密码长度至少6位']);
        }

        if ($new_pwd != $confirm_pwd) {
            return json(['code' => 1, 'message' => '两次登录密码输入不一致']);
        }


        /*if (strlen($new_trad_pwd) < 6) {
            return json(['code' => 1, 'message' => '交易密码长度至少6位']);
        }

        if ($new_trad_pwd != $confirm_trad_pwd) {
            return json(['code' => 1, 'message' => '两次交易密码输入不一致']);
        }*/

        if (!$request->post("code")) {
            return json(['code' => 1, 'message' => '验证码不能为空']);
        }

        $form = new RegisterForm();
        if (!$form->checkChange($request->post('code'), $request->post('mobile'))) {
           return json(['code' => 1, 'message' => '验证码输入错误']);
        }

        $res = User::where("mobile", $mobile)->update([
            "password" => $service->getPassword($new_pwd),
            //"trad_password" => $service->getPassword($new_trad_pwd),
        ]);
        if ($res) {
            return json(['code' => 0, 'message' => '密码修改成功', 'toUrl' => url('publics/index')]);
        } else {
            return json(['code' => 1, 'message' => '密码修改失败']);
        }
    }




    public function aaa()
    {
        $sign = 'rIRoChdErPMr3yUhof3AmUu/to40sY8rEMfMeLEwvuIC+QMd584v6cOub3O0Rv60L8d4ERdSEn0ytr6aVxK6IqJDA3Uf9XE5aOfg3CbsM6vYp/8UgPDH7vsUpe38CDP3gkaqXNrkSFONXlmicFsbKD2cmHXCnqYc9IiQlOnY7+O5VUZF4gMW1HcGqotQSnluITA8mQe1TpKm0ZSwFnWxTM4YFhJfhH9ol9YjHYk5tJ9BaYsnZivOIcclAzCKQjIL2FDEwuE9Dys0ntcadiEY0yvf2z9jW6CgZJLmhGznDgEZWZdMwMKx1SqUVSojya1JRn8APW3Z56/G2ewviVg9Dg==';
        $arr = json_decode('{"jsonData":{"orderDataList":[{"logNo":"N20200608112755199","mercId":"52510225311011D","cashFee":0,"trmNo":"83695367","snNo":"410000052547048395009","cseqNo":"000020","mercFeeAmt":0.76,"ttxnSts":"S","stlAmt":199.24,"stlSts":"S","agtMercNm":"u738bu521a8","txnTm":"20200608104056","agtMercLvl":"4","crdNo":" ","batNo":"060800","txnCdBak":"ALIQRPAY","crdFlg":" ","feeTyp":"1","mercNm":"u4e8eu6625u79c01591341040386","scanFlag":"NEGATIVE","freezeAmt":0,"rowId":1,"agtMercId":"410051240194502","txnCd":"ALIQRPAY","stlTyp":"0","txnAmt":200,"acDt":"20200608"}],"extSeqId":"322324629198868480","agtId":"410051230034082"},"oemId":"410000032000000001","checkValue":"rIRoChdErPMr3yUhof3AmUu/to40sY8rEMfMeLEwvuIC+QMd584v6cOub3O0Rv60L8d4ERdSEn0ytr6aVxK6IqJDA3Uf9XE5aOfg3CbsM6vYp/8UgPDH7vsUpe38CDP3gkaqXNrkSFONXlmicFsbKD2cmHXCnqYc9IiQlOnY7+O5VUZF4gMW1HcGqotQSnluITA8mQe1TpKm0ZSwFnWxTM4YFhJfhH9ol9YjHYk5tJ9BaYsnZivOIcclAzCKQjIL2FDEwuE9Dys0ntcadiEY0yvf2z9jW6CgZJLmhGznDgEZWZdMwMKx1SqUVSojya1JRn8APW3Z56/G2ewviVg9Dg=="
        }',true);

        print_r(verifySign($arr,$sign));
    }
    function sign($data) {
        $certs = array();
        openssl_pkcs12_read(file_get_contents('/www/wwwroot/525kstx/public/test.pfx'), $certs, '888888'); // 其中password为你的证书密码
        if (!$certs) {
            return 0;
        }
        $signature = '';
        openssl_sign($data, $signature, $certs['pkey']);
        return base64_encode($signature);
    }

//证书解密字符串  ，编码加密的字符串

    function verify($data, $signature) {
        $certs = array();
        openssl_pkcs12_read(file_get_contents('/www/wwwroot/525kstx/public/CFCA_ACS_TEST_OCA31.cer'), $certs, '888888');
        if(!$certs) {
            return 0;
        }
        $result = openssl_verify($data, base64_decode($signature), $certs['cert']); // openssl_verify验签成功返回1，失败0，错误返回-1
        return $result;
    }



    /**
     * 文章详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function articleDetail(){

        $info = Article::where('category', 3)->where('status',1)->find();


        $data = [
            'article_id'=>$info['article_id'],
            'category'=>$info['category'],
            'title'=>$info['title'],
            'content'=>$info['content'],
            'create_time'=>$info['create_time'],
            'status'=>$info['status'],
            'sort'=>$info['sort'],
            'start_time'=>$info['start_time'],
            'end_time'=>$info['end_time'],
            'pic'=>$info['pic'],
            'describe'=>$info['describe'],
        ];

        return json(['code' => 0, 'message' => '请求成功', 'info' => $data]);
    }


    public function download_link(){
        return json(['code' => 0, 'message' => '请求成功', 'info' => Config::getValue('download_link')]);
    }

}
